package day23_30;

import java.util.*;

/**
 * @ClassName Repeat
 * @Description TODO
 * @Author clockTown
 * @Date 2021/6/1 21:56
 * @Version 1.0
 */
public class Repeat {
    public static List<Integer> findSubstring(String s, String[] words) {

        List<Integer> res = new LinkedList<>();

        if (words == null || words.length == 0) {
            return res;
        }

        HashMap<String, Integer> map = new HashMap<>();

        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        int sLen = s.length(), wordLen = words[0].length(), wordCount = words.length;

        for (int i = 0; i < sLen - wordLen * wordCount + 1; i++) {

            HashMap<String, Integer> temp = new HashMap<>();

            String cur = s.substring(i, i + wordLen * wordCount);

            int j = 0;

            for (; j < cur.length(); j += wordLen) {

                String curWord = cur.substring(j, j + wordLen);

                if (!map.containsKey(curWord)) {
                    break;
                }

                temp.put(curWord, temp.getOrDefault(curWord, 0) + 1);

                if (temp.get(curWord) > map.get(curWord)) {
                    break;
                }

            }

            if (j == wordLen * wordCount) {
                res.add(i);
            }


        }


        return res;
    }

    public static void main(String[] args) {
        String s = "barfoothefoobarman";
        String [] words = {"foo","bar"};
        List<Integer> substring = findSubstring(s, words);
    }
}
